import re
from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from users.models import Address

from areas.models import Area
from oauth.models import OAuthQQUser
from users.models import User


class AreasSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('id', 'name')


"""
city_id: 140200
district_id: 140212
email: ""
mobile: "13711111111"
place: "asd"
province_id: 140000
receiver: "python"
tel: ""
title: "python"
"""


class AddressSerializers(serializers.ModelSerializer):
    # 显示指明
    city = serializers.StringRelatedField(read_only=True)
    province = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        fields = (
        'city_id', 'district_id', 'province_id', 'email', 'mobile', 'place', 'receiver', 'tel', 'title', 'city',
        'province', 'district','id')

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不匹配')

        return value

    def create(self, validated_data):
        # 获取用户对象
        user = self.context['request'].user


        validated_data['user'] = user
        address = Address.objects.create(**validated_data)

        return address
